<template>
  <div class="chat-page">
    <ResponsiveLayout
      :theme="uiStore.theme"
      :density="uiStore.density"
      :has-client-info="true"
      :show-tabs="true"
      @sidebar-toggle="handleSidebarToggle"
      @client-info-toggle="handleClientInfoToggle"
      @breakpoint-change="handleBreakpointChange"
    >
      <!-- 侧边栏内容 -->
      <template #sidebar="{ collapsed }">
        <BigLeft :collapsed="collapsed" />
      </template>

      <!-- 标题栏内容 -->
      <template #title-bar>
        <TitleBar
          :chat-title="activeChatTitle"
          :client-name="activeClientName"
          :online-status="isClientOnline"
          :actions="titleBarActions"
        />
      </template>

      <!-- 标签页内容 -->
      <template #tabs>
        <Tabs
          :chat-list="chatList"
          :active-chat="activeChatId"
          @chat-select="handleChatSelect"
        />
      </template>

      <!-- 聊天内容 -->
      <template #chat-content>
        <ChatMid />
      </template>

      <!-- 客户信息栏 -->
      <template #client-info="{ visible }">
        <ClientInfo
          v-if="visible"
          :client="currentClient"
          @update-client="handleUpdateClient"
          @show-history="handleShowHistory"
          @show-tag-editor="handleShowTagEditor"
        />
      </template>
    </ResponsiveLayout>

    <!-- 标签编辑器模态框 -->
    <TagEditor
      v-if="showTagEditor"
      :client-tags="currentClient?.tags || []"
      :available-tags="availableTags"
      @close="showTagEditor = false"
      @save="handleSaveTags"
      @create-tag="handleCreateTag"
      @delete-tag="handleDeleteTag"
    />

    <!-- 客户历史记录模态框 -->
    <ClientHistory
      v-if="showClientHistory"
      :client="currentClient"
      @close="showClientHistory = false"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import ResponsiveLayout from '@/components/layout/ResponsiveLayout.vue'
import BigLeft from '@/components/chat/BigLeft.vue'
import TitleBar from '@/components/chat/TitleBar.vue'
import Tabs from '@/components/chat/Tabs.vue'
import ChatMid from '@/components/chat/ChatMid.vue'
import ClientInfo from '@/components/chat/ClientInfo.vue'
import TagEditor from '@/components/chat/TagEditor.vue'
import ClientHistory from '@/components/chat/ClientHistory.vue'

import { useUIStore } from '@/stores/ui'
import { useChatStore } from '@/stores/chat'
import { useClientStore } from '@/stores/client'
import { useUserStore } from '@/stores/user'
import type { ClientData, Tag, ActionButton } from '@/types'

const uiStore = useUIStore()
const chatStore = useChatStore()
const clientStore = useClientStore()
const userStore = useUserStore()

// 模态框状态
const showTagEditor = ref(false)
const showClientHistory = ref(false)

// 计算属性
const activeChatId = computed(() => chatStore.activeChat)
const activeChatData = computed(() => chatStore.activeChatData)
const currentClient = computed(() => clientStore.currentClient)
const chatList = computed(() => chatStore.sortedChatList)
const availableTags = computed(() => clientStore.availableTags)

const activeChatTitle = computed(() => {
  return activeChatData.value?.title || '选择聊天'
})

const activeClientName = computed(() => {
  return currentClient.value?.name || '未知客户'
})

const isClientOnline = computed(() => {
  if (!currentClient.value) return false
  const lastSeen = currentClient.value.lastContactAt || currentClient.value.updatedAt
  const now = new Date()
  const diff = now.getTime() - lastSeen.getTime()
  return diff < 5 * 60 * 1000 // 5分钟内算在线
})

const titleBarActions = computed((): ActionButton[] => [
  {
    id: 'search',
    label: '搜索',
    icon: 'search',
    onClick: () => console.log('搜索')
  },
  {
    id: 'call',
    label: '通话',
    icon: 'phone',
    onClick: () => console.log('发起通话')
  },
  {
    id: 'video',
    label: '视频',
    icon: 'video',
    onClick: () => console.log('发起视频')
  },
  {
    id: 'more',
    label: '更多',
    icon: 'more',
    onClick: () => console.log('更多操作')
  }
])

// 事件处理
const handleSidebarToggle = (visible: boolean) => {
  console.log('侧边栏切换:', visible)
}

const handleClientInfoToggle = (visible: boolean) => {
  console.log('客户信息切换:', visible)
}

const handleBreakpointChange = (breakpoint: string) => {
  console.log('断点变化:', breakpoint)
}

const handleChatSelect = (chatId: string) => {
  chatStore.setActiveChat(chatId)
  
  // 加载对应的客户信息
  const chat = chatStore.chatList.find(c => c.id === chatId)
  if (chat && chat.participants.length > 0) {
    const client = chat.participants.find(p => p.role === 'client')
    if (client) {
      // 这里应该加载完整的客户信息
      // clientStore.loadClient(client.id)
    }
  }
}

const handleUpdateClient = (updates: Partial<ClientData>) => {
  if (currentClient.value) {
    clientStore.updateClient(currentClient.value.id, updates)
  }
}

const handleShowHistory = (clientId: string) => {
  showClientHistory.value = true
}

const handleShowTagEditor = () => {
  showTagEditor.value = true
}

const handleSaveTags = (tags: Tag[]) => {
  if (currentClient.value) {
    handleUpdateClient({ tags })
  }
  showTagEditor.value = false
}

const handleCreateTag = (tag: Omit<Tag, 'id'>) => {
  clientStore.createTag(tag)
}

const handleDeleteTag = (tagId: string) => {
  clientStore.deleteTag(tagId)
}

// 生命周期
onMounted(() => {
  // 初始化数据
  chatStore.initialize()
  clientStore.initialize()
  userStore.initialize()
  uiStore.initialize()
})
</script>

<style scoped>
.chat-page {
  height: 100vh;
  overflow: hidden;
  background: var(--color-background);
}

/* 确保所有子组件都能正确显示 */
:deep(.responsive-layout) {
  height: 100%;
}
</style>